在Web專案裡多少都會遇到檔案上傳到Server或從Server端下載資料的需求,今日就來看看Java EE提供什麼樣子的解決方案
Servlet3.0起新增了Part interface,讓我們可以更簡單的處理檔案上下傳
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024   //1MB The size threshold after which the file will be written to disk
        ,maxFileSize = 5* 1024 * 1024     //5MB The maximum size allowed for uploaded files.
        ,maxRequestSize = 5* 5* 1024 * 1024  //5MB The maximum size allowed for multipart/form-data requests
)
@WebServlet("/UploadFileServlet")
public class UploadFileServlet extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        String filePath =  getServletContext().getRealPath("file_upload") ;
        System.out.println("filePath;"+filePath);
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            String fileName = part.getSubmittedFileName();
            System.out.println("upload filename;"+fileName);
            part.write(filePath+File.separator+fileName);
        }
        System.out.println("file upload success!!");
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo Fileupload and Download</title>
</head>
<body>
    <h5>上傳檔案:</h5>
    <form action="/UploadFileServlet" method="post" enctype="multipart/form-data">
        <input type="file" name="選擇檔案">
        <input type="submit" value="上傳">
    </form>
</body>
</html>
訪問index.html上傳任意檔案
上傳payload
server log
@WebServlet(urlPatterns = "/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String file = "火影忍者.jpg";
        String mimeType = getServletContext().getMimeType(file);
        res.setContentType(mimeType);
        //解決中文檔名問題
        String fileName = URLEncoder.encode(file, "UTF8");
        res.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
        //io stream操作 method1
        String filePath = getServletContext().getRealPath("download")+ File.separator+file;
        FileInputStream is = new FileInputStream(filePath);
        ServletOutputStream outputStream = res.getOutputStream();
        byte[] bytes = is.readAllBytes();
        outputStream.write(bytes);
        is.close();
        //io stream操作 method2
        //getServletContext().getResourceAsStream("/download/"+file).transferTo(res.getOutputStream());
    }
}
index.html增加連結
<h5>下載檔案:</h5>
    <a href="DownloadServlet">Download</a>
